#!/bin/bash

### BEGIN INIT INFO
# Provides:          console.debian
# Required-Start:    $all
# Required-Stop:     $all
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: starts a console daemon
# Description:       starts a console daemon
### END INIT INFO

# Usage instructions:
# - Copy this file to your /etc/init.d directory:
#   $ sudo cp console.sh /etc/init.d/console
# - Initialise the script to survive reboots:
#   $ sudo update-rc.d console defaults
# - Start your server:
#   $ sudo /etc/init.d/console start


NAME="console"
DESC="Starts a cvirt console daemon to run [domain here]"
SITE_DIR=/opt/

PROCESSES=2 # Number of processes to spawn

PORT="80"
HOST="0.0.0.0" # listen on loopback by default
CHUID=""
ACCESS_LOG=/var/log/cvirt-access.log

# END CONFIGURATION
CVIRTCONF=${CVIRTCONF:-"/opt/tcloud/conf.d/manager.run"}

# Don't edit this
PIDFILE=/var/run/console/$NAME.pid
if [ ! -e `dirname $PIDFILE` ]; then
    mkdir -p `dirname $PIDFILE`
fi

test -f "$CVIRTCONF" && . "$CVIRTCONF"

# make sure the access_log file exists
if [ ! -e $ACCESS_LOG ]; then
    mkdir -p `dirname $ACCESS_LOG`
    touch $ACCESS_LOG
fi

start() {
    echo -n "Starting $NAME on $HOST:$PORT... " && echo

    /usr/bin/uwsgi --http $HOST:$PORT $WSGI_APP -p $PROCESSES --plugin python -d $ACCESS_LOG \
    --pidfile $PIDFILE --no-orphans --chdir $SITE_DIR

    # DAEMON_ARGS="--host=$HOST --port=$PORT"
    # DAEMON_ARGS="$DAEMON_ARGS --stderr=$ERROR_LOG --access-log-file=$ACCESS_LOG"
    # [ -n "$PROCESSES" ]  && DAEMON_ARGS="$DAEMON_ARGS --processes=$PROCESSES"
    # [ -n "$FACTORY" ]    && DAEMON_ARGS="$DAEMON_ARGS --factory=$FACTORY"
    # [ -n "$CHUID" ]      && DAEMON_ARGS="$DAEMON_ARGS --chuid=$CHUID"
    # [ -n "$EXTRA_ARGS" ] && DAEMON_ARGS="$DAEMON_ARGS $EXTRA_ARGS"
    # DAEMON_ARGS="$DAEMON_ARGS $APP"
    # echo "/sbin/start-stop-daemon --start --background --make-pidfile --pidfile=$PIDFILE --chdir $SITE_DIR --exec $SPAWNING_BIN -- $DAEMON_ARGS || return 2"
    # /sbin/start-stop-daemon --start --background --make-pidfile --pidfile=$PIDFILE --chdir $SITE_DIR --exec $SPAWNING_BIN -- $DAEMON_ARGS || return 2
    # echo $NAME
    return 0
}

stop () {
    echo -n "Stopping $NAME: " && echo
    # /sbin/start-stop-daemon --stop --pidfile $PIDFILE
    # uwsgi --stop $PIDFILE
    killall -9 uwsgi
    rm -f $PIDFILE

    return
}

status() {
    if [ -f "$PIDFILE" ]; then
        echo -n "$NAME already running with PIDs: " && cat $PIDFILE && echo
    else
        echo "$NAME not running"
    fi
    return
}

case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    status)
        status
        ;;
    restart)
        stop
        sleep 1
        start
        ;;
    *)
        echo "Usage: $NAME (start|stop|status|restart)"
        exit 1
        ;;
esac
exit $?
